//
//  ViewController.m
//  WaterfallsFlowDemo
//
//  Created by CyanXu on 2022/3/4.
//

#import "ViewController.h"
#import "WaterFallsLayout.h"
#import "WaterFallsCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,WaterFallsLayoutDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)WaterFallsLayout *layout;
@property (nonatomic, strong) NSMutableDictionary *cellDic;

@property(nonatomic,assign)CGFloat itemWidth;

@property(nonatomic,strong)NSMutableArray *datas;

@end

@implementation ViewController
//获取随机颜色数组
- (NSMutableArray *)generalColors:(NSInteger )count{
    NSMutableArray<UIColor *> *colors = [NSMutableArray array];
    for (int i = 0; i< count; i++) {
        CGFloat red = arc4random_uniform(255) + 1;
        CGFloat green = arc4random_uniform(255) + 1;
        CGFloat blue = arc4random_uniform(255) + 1;
        UIColor *randomColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
        
        [colors addObject:randomColor];
    }
    return colors;
}
//获取随机价格
- (NSString *)generalPrice{
    CGFloat random = (arc4random_uniform(1000)+500)*2;
    NSString *priceStr = [NSString stringWithFormat:@"￥%ld",(long)random];
    
    return priceStr;
}
//获取随机购买量
- (NSString *)generalSaleNum{
    CGFloat random = (arc4random_uniform(1000)+500)*2;
    NSString *saleStr = [NSString stringWithFormat:@"%ld+人付款",(long)random];
    
    return saleStr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    self.cellDic = [[NSMutableDictionary alloc] init];
    self.datas = [NSMutableArray array];
    NSArray *imageArray = @[
                            @"http://g.hiphotos.baidu.com/image/w%3D310/sign=6f9ce22079ec54e741ec1c1f89399bfd/9d82d158ccbf6c81cea943f6be3eb13533fa4015.jpg",
                            @"http://b.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31cc6476eb985d6277f9e2ff8bd.jpg",
                            @"http://c.hiphotos.baidu.com/image/pic/item/94cad1c8a786c9174d18e030cb3d70cf3bc7579b.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=79bc1b1a950a304e5222a6fbe1c9a7c3/d1160924ab18972b50a46fd4e4cd7b899e510a15.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=05e2c867272dd42a5f0907aa333a5b2f/7dd98d1001e93901f3f7103079ec54e737d196c3.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=3914596cf1deb48ffb69a7dfc01e3aef/d0c8a786c9177f3ea3e73f0072cf3bc79e3d56e8.jpg",
//                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=8cc67b8cc91349547e1eee65664e92dd/4610b912c8fcc3ce11e40a3e9045d688d43f2093.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=93e1c429952bd40742c7d5fc4b889e9c/3812b31bb051f8191cdd594bd8b44aed2e73e733.jpg",
                            @"http://b.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31cc6476eb985d6277f9e2ff8bd.jpg",
                            @"http://c.hiphotos.baidu.com/image/pic/item/94cad1c8a786c9174d18e030cb3d70cf3bc7579b.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=3914596cf1deb48ffb69a7dfc01e3aef/d0c8a786c9177f3ea3e73f0072cf3bc79e3d56e8.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=93e1c429952bd40742c7d5fc4b889e9c/3812b31bb051f8191cdd594bd8b44aed2e73e733.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=d4507def9d3df8dca63d8990fd1072bf/d833c895d143ad4b758c35d880025aafa40f0603.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=702acce2552c11dfded1b92253266255/d62a6059252dd42a3ac70aaa013b5bb5c8eab8e0.jpg",
                            @"http://h.hiphotos.baidu.com/image/w%3D310/sign=75ff59cd19d5ad6eaaf962ebb1ca39a3/b64543a98226cffcb9f3ddbbbb014a90f703eada.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=11386163f1deb48ffb69a7dfc01e3aef/d0c8a786c9177f3e8bcb070f72cf3bc79f3d5631.jpg",
                            @"http://f.hiphotos.baidu.com/image/w%3D310/sign=8ed508bbd358ccbf1bbcb33b29d8bcd4/8694a4c27d1ed21b33ff8fecaf6eddc451da3f80.jpg",
                            @"http://b.hiphotos.baidu.com/image/w%3D310/sign=ad40ca82c9ef76093c0b9f9e1edca301/5d6034a85edf8db16aa7b27b0b23dd54564e7420.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=79bc1b1a950a304e5222a6fbe1c9a7c3/d1160924ab18972b50a46fd4e4cd7b899e510a15.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D310/sign=05e2c867272dd42a5f0907aa333a5b2f/7dd98d1001e93901f3f7103079ec54e737d196c3.jpg",
                            @"http://g.hiphotos.baidu.com/image/w%3D310/sign=6f9ce22079ec54e741ec1c1f89399bfd/9d82d158ccbf6c81cea943f6be3eb13533fa4015.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=79bc1b1a950a304e5222a6fbe1c9a7c3/d1160924ab18972b50a46fd4e4cd7b899e510a15.jpg",
                            @"http://e.hiphotos.baidu.com/image/w%3D310/sign=79bc1b1a950a304e5222a6fbe1c9a7c3/d1160924ab18972b50a46fd4e4cd7b899e510a15.jpg"
                            ];
//    NSArray *imageArray = @[@"cat1.jpg",@"cat2.jpg",@"cat3.jpg",@"cat4.jpg",@"cat1.jpg",@"cat2.jpg",@"cat3.jpg",@"cat4.jpg",@"cat1.jpg",@"cat2.jpg",@"cat3.jpg",@"cat4.jpg",@"cat1.jpg",@"cat2.jpg",@"cat3.jpg",@"cat4.jpg"];
    
    NSString *content = @"标题";
    for (int i=0; i<imageArray.count; i++) {
        WaterFallsModel *model = [[WaterFallsModel alloc] init];
        model.imageUrl = imageArray[i];
        model.title = [NSString stringWithFormat:@"%@-%d-%@",content,i,imageArray[i]];
        CGRect rect1 = [model.title boundingRectWithSize:CGSizeMake((width-15)/2 -5, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]} context:nil];
        model.titleHeight = rect1.size.height;
        
        model.price = [self generalPrice];
        model.saleNum = [self generalSaleNum];
        
        CGRect rect2 = [model.price boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16.0f]} context:nil];
        model.priceHeight = rect2.size.height+5;
        model.priceWidth = rect2.size.width+5;
        
        CGRect rect3 = [model.saleNum boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13.0f]} context:nil];
        model.saleWidth = rect3.size.width+ 10;
        
        
        [self.datas addObject:model];
    }

    self.itemWidth = (width - 3*16)/2;
    
    self.layout = [[WaterFallsLayout alloc] init];
    self.layout.width = width;
    self.layout.delegate = self;
    self.layout.minimumInteritemSpacing = 5;
    self.layout.minimumLineSpacing = 5;
    

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, width, self.view.bounds.size.height+30) collectionViewLayout:self.layout];
    self.collectionView.backgroundColor = [UIColor grayColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
//    [self.collectionView registerClass:[WaterFallsCell class] forCellWithReuseIdentifier:@"CollectionViewCellId"];
    [self.view addSubview:self.collectionView];
}


- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    //为了解决复用问题 每个cell都重新注册  性能消耗会大一点
    NSString *identifier = [_cellDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section,(long)indexPath.row];
        [_cellDic setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        // 注册Cell
        [self.collectionView registerClass:[WaterFallsCell class]  forCellWithReuseIdentifier:identifier];
    }
    
    WaterFallsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    WaterFallsModel *model = self.datas[indexPath.row];
    CGFloat cellWidth = cell.contentView.bounds.size.width;
    
    //加载本地图片
//    UIImage *image = [UIImage imageNamed:model.imageUrl];
//    [cell.imageView setImage:image];
//    if (model.imageHeight == 0) {
//        NSLog(@"row=%ld",(long)indexPath.row);
//
//        CGFloat rate = image.size.width/cellWidth;
//        model.imageHeight = image.size.height/rate;
//        cell.model = model;
//
//        [self.layout.cache removeAllObjects];
//        self.layout.contentHeight = 0;
//        [self.layout invalidateLayout];
//
//    }
    
    //加载网络图片
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imageUrl] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        NSLog(@"%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (image) {
                if (model.imageHeight == 0) {
                    //已经布局过的不再刷新  减少内存消耗
                    CGFloat rate = image.size.width/cellWidth;
                    //如果想固定图片高度，写死model.imageHeight就可以了
                    model.imageHeight = image.size.height/rate;
                    cell.model = model;
                    //每次加载后重新刷新界面布局
                    [self.layout.cache removeAllObjects];
                    self.layout.contentHeight = 0;
                    //这个会重新刷新prepareLayout  然后heightForItemAtIndexPath重新计算frame布局
                    [self.layout invalidateLayout];
                }
            }
        });
    }];
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.datas.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView heightForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterFallsModel *model = [self.datas objectAtIndex:indexPath.row];
    if (model.imageHeight != 0) {
        NSLog(@"row=%ld  ImageHeight=%.1f  labelHeight=%.1f",(long)indexPath.row,model.imageHeight,  model.titleHeight+model.priceHeight);
        return (model.imageHeight + model.titleHeight + model.priceHeight+20);
    }
    return 100;
}
@end
